package com.cti.ftpservice.ftp;
import java.io.File;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.cti.ftpservice.ftp.CommonsFtpUtils.DownloadStatus;
import com.cti.ftpservice.vo.FtpFileInfoVo;
import com.cti.ftpservice.vo.FtpServiceDownloadInfoVo;


public class FTPDownFiles  implements Runnable {

    private FtpServiceDownloadInfoVo ftpDownLoadParams;
	private static Log logger = LogFactory.getLog(FTPDownFiles.class);
	public FTPDownFiles(FtpServiceDownloadInfoVo _ftpDownLoadParams){
		ftpDownLoadParams=_ftpDownLoadParams;
	}
	@Override
	public void run() {
		FtpFileInfoVo downPath=null;
		try {
			 if(ftpDownLoadParams==null){
				 return;
			 }
			 while(!ftpDownLoadParams.getStop()){
				 try {
					 if(ftpDownLoadParams.getDealCount()==ftpDownLoadParams.getBookTotalCount()){
						 ftpDownLoadParams.stopDownLoadFiles();
						 logger.info("文件全部下载完成");
					 }
					 while(ftpDownLoadParams.getPause()){
						 wait();
					 }
					 while ((downPath=ftpDownLoadParams.getFirstDownloadFilePath())==null) {
						ftpDownLoadParams.stopDownLoadFiles();
						return;
					}
					 if(downPath!=null){
						 File file=new File(downPath.getLocalFtpPath());
						 boolean download=true;
						 if(file.exists()&&file.length()>=downPath.getFileSize())
							 download=false;
						 if(download){
							 FTPClientHelper ftpClient=new FTPClientHelper();
							 if(!ftpClient.isConnected())
							    CommonsFtpUtils.connect(ftpClient,ftpDownLoadParams.getFtpURL(), new java.lang.Integer(ftpDownLoadParams.getFtpport()), ftpDownLoadParams.getUsername(), ftpDownLoadParams.getPwd());
							 DownloadStatus status=CommonsFtpUtils.download(ftpClient,downPath.getFtpServicePath(),downPath.getLocalFtpPath());
							 CommonsFtpUtils.disconnect(ftpClient);
							 if(status!=DownloadStatus.Local_Bigger_Remote&&status!=DownloadStatus.Download_From_Break_Failed&&status!=DownloadStatus.Download_New_Failed)
								 logger.info(Thread.currentThread().getName()+"成功下载文件："+downPath.getFileName()+"; 已经处理"+(ftpDownLoadParams.getDealCount()+1)+"个文件");
						 }else{
							 logger.info(Thread.currentThread().getName()+"成功下载文件："+downPath.getFileName()+"; 已经处理"+(ftpDownLoadParams.getDealCount()+1)+"个文件");
						 }
						 ftpDownLoadParams.adddealItem(downPath,true); 
				  }
				  Thread.yield(); 
			      if (Thread.currentThread().isInterrupted()) {
			             throw new InterruptedException("Stopped by if Interrupted Stop()");
			      }
				} catch (Exception e) {
					if(downPath!=null)
						 ftpDownLoadParams.addDownloadFilePath(downPath);
				    logger.info(Thread.currentThread().getName()+e.getMessage());
				}
	       } 
		} catch (Exception e) {
			 ftpDownLoadParams.clearDealFiles();
			 logger.info(Thread.currentThread().getName()+e.getMessage());	
		}
	}
}
